import base64
import os

import ddddocr


class Images:
    def __init__(self, imgStr, imgName):
        self.imgStr = imgStr
        self.imgName = imgName

    # 图片转base64,返回base64编码结果
    def imageToBase64(self):
        with open(self.imgStr, "rb") as f:  # 转为二进制形式读取图片
            base64_data = base64.b64encode(f.read())  # 使用base64进行加密
        return base64_data

    # base64转图片并保存，imgStr是base64字符串，imgName文件名
    def base64ToImage(self):
        imgdata = base64.b64decode(self.imgStr)
        with open(self.imgName, 'wb') as fp:
            fp.write(imgdata)
        return self.base64ocr()

    def base64ocr(self):
        ocr = ddddocr.DdddOcr(show_ad=False)  # 实例化
        with open(self.imgName, 'rb') as f:  # 打开图片
            img_bytes = f.read()  # 读取图片
        res = ocr.classification(img_bytes)  # 识别

        result = eval("{a} {x} {b}".format(a=res[0], x=res[1], b=res[2]))
        return result  # 验证码计算数

    def base(self, string):
        encoder = base64.b64encode(string.encode("utf-8")).decode('utf-8')  # byte类型 b'5oiR5piv5LiA5Liq5a2X56ym5Liy'
        # str_encoder = encoder.decode('utf-8')
        return encoder
